package com.yhy.common.redis.config;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.TransportMode;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

@Slf4j
@RequiredArgsConstructor
public class RedissonConfig {

    private final RedissonConfigProperties redissonConfigProperties;

    /**
     * 配置redisson集群
     */
    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(prefix = "redisson", name = "model", havingValue = "CLUSTER")
    public RedissonClient getRedissonClient() {
        RedissonConfigProperties.Cluster clusters = redissonConfigProperties.getClusters();
        String[] nodes = clusters.getNodes();
        String password = clusters.getPassword();

        Config config = new Config();
        // 对象编码选择纯字符串编码
        config.setCodec(StringCodec.INSTANCE);
        ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(nodes);
        // 设置密码
        clusterServersConfig.setPassword(password);
        // redis连接心跳检测，防止一段时间过后，与redis的连接断开
        clusterServersConfig.setPingConnectionInterval(32000);
        RedissonClient redissonClient = Redisson.create(config);
        log.debug("The Redisson starts in cluster mode: {}", JSONUtil.toJsonStr(clusters));
        return redissonClient;
    }

    /**
     * 单机配置
     */
    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(prefix = "redisson", name = "model", havingValue = "SINGLE")
    RedissonClient singleRedisson() {
        RedissonConfigProperties.Single single = redissonConfigProperties.getSingle();
        // 创建配置
        Config config = new Config();
        config.setCodec(StringCodec.INSTANCE);
        config.setTransportMode(TransportMode.NIO);
        config.useSingleServer()
                .setAddress(single.getAddress())
                .setPassword(single.getPassword())
                .setDatabase(single.getDatabase());
        RedissonClient redissonClient = Redisson.create(config);
        log.debug("The Redisson starts in stand-alone mode: {}", JSONUtil.toJsonStr(single));
        return redissonClient;
    }
}
